package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Family;
import com.example.demo.mapper.FamilyMapper;
import com.example.demo.mapper.Stu_FamMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * @author lai
 * @data 2021/11/17
 * @apiNote
 */
@RestController
@RequestMapping("/family")
public class FamilyController {

    @Resource
    FamilyMapper familyMapper;

    @Resource
    Stu_FamMapper stu_famMapper;


    /**
     * 对数据库的插入与更新
     *
     * family：要插入的家长对象
     * stuId：当前学生账号的id
     * */
    @PostMapping("/inster/{stuId}")
    public Result<?> save(@RequestBody Family family, @PathVariable Integer stuId){
        Result result;
        try {
            if (family.getId() == null){
                familyMapper.insert(family);
                stu_famMapper.insert(stuId,family.getId());
            }
            else {
                updata(family);
            }
            result = Result.success();
        }catch (Exception e){
            result = Result.fail();
        }
        return result;
    }

    /**
     * 根据学生id查找该学生的家长
     *
     * id：当前学生账号的id
     * */
    @GetMapping("/{id}")
    public Result<?> find(@PathVariable Integer id){
        return Result.success(familyMapper.findfamily(id));
    }

    /**
     *更新家长表
     *
     * family：要更新的家长的对象信息
     */
    public void updata( Family family){
        Family test = new Family();
        test.setId(family.getId());
        test = family;
        familyMapper.updateById(test);
    }

    /**
     * 根据学生和家长的id删除关系表
     *
     * stuId: 当前账号的学生id
     * famId: 要删除的家长的id
     * */
    @DeleteMapping("/"+"{stuId}"+"&"+"{famId}")
    public Result<?> delete(@PathVariable Integer famId, @PathVariable Integer stuId){
        Result result ;
        try {
            stu_famMapper.delete1(stuId,famId);
            // 如果关系表里没有这个家长的关系了，就直接删去这个家长的信息
            if (stu_famMapper.selectByFamilyId(famId)==null){
                familyMapper.deleteById(famId);
            }
            result = Result.success();
        }catch (Exception e){
            result = Result.fail();
            System.out.println(e);
        }
        return result;
    }

    /**
     * 头像上传
     *
     * id：更改头像的用户的id
     * portrait：头像地址
     * */
    @PostMapping("/portrait/"+"{id}"+"&"+"{portrait}")
    public Result<?> insertPortrait(@PathVariable Integer id,@PathVariable String portrait){
        Result result;
        try {
            portrait = portrait.replaceAll("，","/").replace("。","http://localhost:9090");
            Family family = new Family();
            family.setId(id);
            family.setPortrait(portrait);
            familyMapper.updateById(family);

            result = Result.success();
        }catch (Exception e){
            result = Result.fail();
            System.out.println(e);
        }
        return result;
    }
}
